#!/bin/bash

# 安装脚本依赖软件包
sudo apt install -y debootstrap qemu-user-static zerofree rsync p7zip-full

#需要安装的软件包
PKGS=openssh-server,systemd-timesyncd,lrzsz,ca-certificates,dbus,iwd,wireless-regdb

# 创建镜像文件
rm -f rootfs.ext4
dd if=/dev/zero of=rootfs.ext4 bs=1M count=512 status=progress
sudo mkfs.ext4 rootfs.ext4

# 安装根文件系统
sudo rm -rf rootfs
sudo mkdir -p rootfs
sudo mount -o loop rootfs.ext4 rootfs
sudo debootstrap --arch armhf --include=$PKGS bullseye rootfs/ http://mirrors.ustc.edu.cn/debian

# 修改主机名
echo fsmp1a | sudo tee rootfs/etc/hostname

# 使用systemd解析名字
sudo rm -f rootfs/etc/resolv.conf
sudo ln -sf /run/systemd/resolve/stub-resolv.conf rootfs/etc/resolv.conf

# 修改时区
echo 'Asia/Shanghai' | sudo tee rootfs/etc/timezone
sudo ln -snf /usr/share/zoneinfo/Asia/Shanghai rootfs/etc/localtime

# 复制文件
sudo rsync -Krv files/* rootfs

# 删除machine-id
sudo rm -f rootfs/etc/machine-id

# 修改安装脚本权限
sudo chmod +x rootfs/root/setup.sh

# 修改root用户密码
PASS_HASH=$(openssl passwd -6 "hqyj")
sudo sed -i "s|^root:[^:]*:|root:$PASS_HASH:|" rootfs/etc/shadow

# 修改sshd配置，允许root用户登录
sudo sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' rootfs/etc/ssh/sshd_config

# 修改fstab
UUID=$(sudo blkid -s UUID -o value rootfs.ext4)
echo "UUID=$UUID / ext4 noatime 0 1" | sudo tee rootfs/etc/fstab

# 启用电源键
sudo sed -i 's/#HandlePowerKey=poweroff/HandlePowerKey=poweroff/' rootfs/etc/systemd/logind.conf

# 卸载根文件系统并删除挂载目录
sudo umount rootfs
sudo rm -r rootfs

# 清理镜像中删除的文件，减少压缩文件大小
sudo zerofree -v rootfs.ext4

# 将根文件系统镜像复制到boot目录并打包压缩
target_dir="debian11-fsmp1a-$(date +'%Y.%m.%d')"
cp -a ../images .
mv rootfs.ext4 images
mv images $target_dir
rm -f $target_dir.7z
7z a $target_dir.7z $target_dir && rm -r $target_dir
